package org.jeecg.community.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.autopoi.poi.excel.ExcelImportUtil;
import org.jeecg.autopoi.poi.excel.def.NormalExcelConstants;
import org.jeecg.autopoi.poi.excel.entity.ExportParams;
import org.jeecg.autopoi.poi.excel.entity.ImportParams;
import org.jeecg.autopoi.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.community.entity.XyParkHousecapital;
import org.jeecg.community.entity.XyParkHousestay;
import org.jeecg.community.entity.XyParkHouse;
import org.jeecg.community.vo.HouseTreeNode;
import org.jeecg.community.vo.XyParkHousePage;
import org.jeecg.community.service.IXyParkHouseService;
import org.jeecg.community.service.IXyParkHousecapitalService;
import org.jeecg.community.service.IXyParkHousestayService;
import org.jeecg.community.vo.XyParkHouseWithContractInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * 房源信息
 * @author: jeecg-boot
 * @version: V1.0
 */
@Api(tags="园区物业-房源信息")
@RestController
@RequestMapping("/community/xyParkHouse")
@Slf4j
public class XyParkHouseController {
	@Autowired
	private IXyParkHouseService xyParkHouseService;
	@Autowired
	private IXyParkHousecapitalService xyParkHousecapitalService;
	@Autowired
	private IXyParkHousestayService xyParkHousestayService;
	
	/**
	 * 分页列表查询
	 *
	 * @param xyParkHouse
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "房源信息-分页列表查询")
	@ApiOperation(value="房源信息-分页列表查询", notes="房源信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(XyParkHouse xyParkHouse,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<XyParkHouse> queryWrapper = QueryGenerator.initQueryWrapper(xyParkHouse, req.getParameterMap());
		Page<XyParkHouse> page = new Page<XyParkHouse>(pageNo, pageSize);
		IPage<XyParkHouse> pageList = xyParkHouseService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param xyParkHousePage
	 * @return
	 */
	@AutoLog(value = "房源信息-添加")
	@ApiOperation(value="房源信息-添加", notes="房源信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody XyParkHousePage xyParkHousePage) {
		XyParkHouse xyParkHouse = new XyParkHouse();
		BeanUtils.copyProperties(xyParkHousePage, xyParkHouse);
		xyParkHouseService.saveMain(xyParkHouse, xyParkHousePage.getXyParkHousecapitalList(),xyParkHousePage.getXyParkHousestayList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param xyParkHousePage
	 * @return
	 */
	@AutoLog(value = "房源信息-编辑")
	@ApiOperation(value="房源信息-编辑", notes="房源信息-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody XyParkHousePage xyParkHousePage) {
		XyParkHouse xyParkHouse = new XyParkHouse();
		BeanUtils.copyProperties(xyParkHousePage, xyParkHouse);
		XyParkHouse xyParkHouseEntity = xyParkHouseService.getById(xyParkHouse.getId());
		if(xyParkHouseEntity==null) {
			return Result.error("未找到对应数据");
		}
		xyParkHouseService.updateMain(xyParkHouse, xyParkHousePage.getXyParkHousecapitalList(),xyParkHousePage.getXyParkHousestayList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "房源信息-通过id删除")
	@ApiOperation(value="房源信息-通过id删除", notes="房源信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		xyParkHouseService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "房源信息-批量删除")
	@ApiOperation(value="房源信息-批量删除", notes="房源信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.xyParkHouseService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "房源信息-通过id查询")
	@ApiOperation(value="房源信息-通过id查询", notes="房源信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		XyParkHouse xyParkHouse = xyParkHouseService.getById(id);
		if(xyParkHouse==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(xyParkHouse);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "房源配属资产通过主表ID查询")
	@ApiOperation(value="房源配属资产主表ID查询", notes="房源配属资产-通主表ID查询")
	@GetMapping(value = "/queryXyParkHousecapitalByMainId")
	public Result<?> queryXyParkHousecapitalListByMainId(@RequestParam(name="id",required=true) String id) {
		List<XyParkHousecapital> xyParkHousecapitalList = xyParkHousecapitalService.selectByMainId(id);
		return Result.OK(xyParkHousecapitalList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "房源住宿信息通过主表ID查询")
	@ApiOperation(value="房源住宿信息主表ID查询", notes="房源住宿信息-通主表ID查询")
	@GetMapping(value = "/queryXyParkHousestayByMainId")
	public Result<?> queryXyParkHousestayListByMainId(@RequestParam(name="id",required=true) String id) {
		List<XyParkHousestay> xyParkHousestayList = xyParkHousestayService.selectByMainId(id);
		return Result.OK(xyParkHousestayList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param xyParkHouse
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XyParkHouse xyParkHouse) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<XyParkHouse> queryWrapper = QueryGenerator.initQueryWrapper(xyParkHouse, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<XyParkHouse> queryList = xyParkHouseService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<XyParkHouse> xyParkHouseList = new ArrayList<XyParkHouse>();
      if(oConvertUtils.isEmpty(selections)) {
          xyParkHouseList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          xyParkHouseList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<XyParkHousePage> pageList = new ArrayList<XyParkHousePage>();
      for (XyParkHouse main : xyParkHouseList) {
          XyParkHousePage vo = new XyParkHousePage();
          BeanUtils.copyProperties(main, vo);
          List<XyParkHousecapital> xyParkHousecapitalList = xyParkHousecapitalService.selectByMainId(main.getId());
          vo.setXyParkHousecapitalList(xyParkHousecapitalList);
          List<XyParkHousestay> xyParkHousestayList = xyParkHousestayService.selectByMainId(main.getId());
          vo.setXyParkHousestayList(xyParkHousestayList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "房源信息列表");
      mv.addObject(NormalExcelConstants.CLASS, XyParkHousePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("房源信息数据", "导出人:"+sysUser.getRealname(), "房源信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<XyParkHousePage> list = ExcelImportUtil.importExcel(file.getInputStream(), XyParkHousePage.class, params);
              for (XyParkHousePage page : list) {
                  XyParkHouse po = new XyParkHouse();
                  BeanUtils.copyProperties(page, po);
                  xyParkHouseService.saveMain(po, page.getXyParkHousecapitalList(),page.getXyParkHousestayList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * create by: wpp
	  * description:
	  * 获取 项目、楼宇、楼层 虚拟树
	  * create time: 2022/01/14 20:49
	  * @Param: 节点ID
	  * @return com.alibaba.fastjson.JSONArray
	  */
	 @GetMapping(value = "/getHouseTree")
	 public Result<?> getHouseTree(@RequestParam(name="id",required=false) Long id){
		 JSONArray arr=new JSONArray();
		 List<HouseTreeNode> houseTree = xyParkHouseService.getHouseTree(id);
		 if(houseTree!=null&&houseTree.size()>0){
			 for(HouseTreeNode node:houseTree){
				 String str= JSON.toJSONString(node);
				 JSONObject obj=JSON.parseObject(str);
				 arr.add(obj);
			 }
		 }
		return Result.OK(arr);
	 }

	 /**
	  * create by: wpp
	  * description:
	  * 根据上一步的节点树信息及检索条件过滤查询
	  * create time: 2022/01/18 20:49
	  * @Param:
	  * @return XyParkHouseWithContractInfoVo
	  */
	 @RequestMapping(value = "/queryHouseContractListByTreeNode", method = RequestMethod.GET)
	 public Result<Page<XyParkHouseWithContractInfoVo>> queryHouseContractListByTreeNode(XyParkHouseWithContractInfoVo house,
																	  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																	  HttpServletRequest req) throws ParseException {
		 Result<Page<XyParkHouseWithContractInfoVo>> result = new Result<Page<XyParkHouseWithContractInfoVo>>();
		 Page<XyParkHouseWithContractInfoVo> pageList = new Page<XyParkHouseWithContractInfoVo>(pageNo,pageSize);
		 XyParkHouseWithContractInfoVo queryEntity = new XyParkHouseWithContractInfoVo();
		 queryEntity.setProject(house.getProject());
		 queryEntity.setBuilding(house.getBuilding());
		 queryEntity.setFloor(house.getFloor());
		 queryEntity.setContractCode(house.getContractCode());
		 queryEntity.setContractOwnerName(house.getContractOwnerName());
		 queryEntity.setHouseStatus(house.getHouseStatus());//房源状态
		 Map<String, String[]> parameterMap = req.getParameterMap();
		 if (parameterMap != null && parameterMap.containsKey("contractSigningDate_begin_str")) {
			 String beginValue = parameterMap.get("contractSigningDate_begin_str")[0].trim();
			 queryEntity.setContractSigningDate_begin(DateUtils.parseDate(beginValue,"yyyy-MM-dd"));
		 }
		 if (parameterMap != null && parameterMap.containsKey("contractSigningDate_end_str")) {
			 String endValue = parameterMap.get("contractSigningDate_end_str")[0].trim();
			 queryEntity.setContractSigningDate_end(DateUtils.parseDate(endValue,"yyyy-MM-dd"));
		 }
		 if (parameterMap != null && parameterMap.containsKey("contractEndDate_begin_str")) {
			 String beginValue = parameterMap.get("contractEndDate_begin_str")[0].trim();
			 queryEntity.setContractEndDate_begin(DateUtils.parseDate(beginValue,"yyyy-MM-dd"));
		 }
		 if (parameterMap != null && parameterMap.containsKey("contractEndDate_end_str")) {
			 String endValue = parameterMap.get("contractEndDate_end_str")[0].trim();
			 queryEntity.setContractEndDate_end(DateUtils.parseDate(endValue,"yyyy-MM-dd"));
		 }
		 pageList = xyParkHouseService.queryHouseContractListByTreeNode(pageList,queryEntity);//通知公告消息
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }
}
